package com.ruoyi.web.controller.file;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class VideoDownloader {

    // 缓冲区大小，8KB
    private static final int BUFFER_SIZE = 8192;

    public static void main(String[] args) {
        // 视频的HTTP URL
        String videoUrl = "https://stream.aipark.top/download?payload=FltZHQgWB1kKCAlPQw9FUkZDG1NTSllPGEddUVgPHhcVT0MPHBEHBF5RSlYfHEkdFxYXWQQXVwoWQhMJFgJEDwAWQxpCGUoFHUkOCgkBGFQWBBAfEg4dCQQLSElUREEaXFVOVE0bKBBDRB9dABBQKkQGIBI5GgEkCxs1VyQWI0xyGQlLPChxAVVDRhsCFURcThtaVF1FFF5LSFUlWERVQUJED1gWQDhgHR8iTXxTChwXLFsxHCYHVQw9ASRLQkQkBSNALFc9BkAUPg8ZM2BdVShcJVhEVUFCRB8EHlBIHkM5BkQdWVMYBA1MExZORR5YQEsuSB5AQEE3HFhQXF86HEdTVkZuWlZOSEtuRVNDUR8oV01fXB83V0dHCFkmS1lNCEYmQUAaTlc6X00VUVcwRhpTQEsuShRBQEE3HlJTXF86Hk1SVkZuWFxBSEtuR1xKUR8oUEBVXB83UkRNCFkmTlVJCEYmREwVNxBJXUsbBwoGBk4OWAACDFkBBxYoWFtVS1sLSAUQGgZIGBYVUABIBzkGRB1ZUwEdGhAxAiUbHwohKiMoCEchVkdpNxBJXUsbGQAHSRxcUE5bQRtHUUVRHyg5DF1JH0IIG0l%2FGjkMXUkfQggeSR5aQEsuSxQoEENEH10IF1AKQ1kQCxVVXxMWHRMYBR1eBR0FU1xfOl4aSEcTGAcfFwgLcQFVQ0YbBhZEDAwIRiYBEFg3EEldSxsZE04ZcR5VSV9PQAIMTkdxHlVJX09dGFhBR3EeVUlfT18ZFk4VWE5XOgwMcQFVQ0YbAgsQGRpaGgERBF5WVE5ZShpBVS8BHVtXTw8MREkkKkVHEik0ClRjIlEWK0gYKxE9HnktEEQmWA4ODCc2XRIEOAxsEl0qHzEYQ1IZPVUAMEA5VHw3NkYCe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hYiQzgXABQqGgATFy10HjcyCQBOADAqEHcyMxgGSx0sNR4xZwIvACEMZDUmOiVpET0XXE1UE11HMUYPKk8iH2U9BAVZbzwiQFsYGkMxJjJJMiIDITIVFjZAJQhYIVxePXEBVUNGGxsKDVA0QxUjFyZKWQhMXzRcGzM%2FIh8KUB4kS2IdXSseHAgzFglKFCZVHxtXWzwuBBhrGFA4KxwoHTscTx8kDBYkGCQcCwwVXTMnMkVbMVwuIwxbGjABMBsuNjI5DUoENhJCGANWK1UmfjMpOi1aWAASCAhoRQIUEn4mVkwdPhsnKSwxRyM2FgQ%2FR0IDBCJIXgRKCAx%2FBj8pGl8yNUgUCGowMkAuDxY%3D";
        // 保存到本地的文件路径
        String saveFilePath = "downloaded_video.mp4";

        try {
            downloadVideo(videoUrl, saveFilePath);
            System.out.println("视频下载完成！");
        } catch (IOException e) {
            System.err.println("下载过程中发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 从指定URL下载视频并保存到本地文件
     * @param videoUrl 视频的HTTP URL
     * @param saveFilePath 保存到本地的文件路径
     * @throws IOException 如果发生网络或文件操作错误
     */
    public static void downloadVideo(String videoUrl, String saveFilePath) throws IOException {
        URL url = new URL(videoUrl);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();

        // 设置请求方法
        httpConn.setRequestMethod("GET");
        // 设置超时时间（毫秒）
        httpConn.setConnectTimeout(5000);
        httpConn.setReadTimeout(15000);

        int responseCode = httpConn.getResponseCode();

        // 检查是否成功连接 (HTTP 200 OK)
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 获取输入流
            InputStream inputStream = httpConn.getInputStream();
            // 创建文件输出流
            FileOutputStream outputStream = new FileOutputStream(saveFilePath);

            byte[] buffer = new byte[BUFFER_SIZE];
            int bytesRead;
            long totalBytesRead = 0;

            // 获取文件大小（如果服务器提供了）
            long fileSize = httpConn.getContentLengthLong();
            System.out.println("文件大小: " + formatFileSize(fileSize));

            // 读取数据并写入文件
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
                totalBytesRead += bytesRead;

                // 显示下载进度
                if (fileSize > 0) {
                    int progress = (int) (totalBytesRead * 100 / fileSize);
                    System.out.print("\r下载进度: " + progress + "%");
                }
            }

            // 关闭流
            outputStream.close();
            inputStream.close();
            System.out.println(); // 换行

        } else {
            throw new IOException("服务器返回非成功状态码: " + responseCode);
        }

        httpConn.disconnect();
    }

    /**
     * 将字节大小格式化为人类可读的格式
     * @param bytes 字节数
     * @return 格式化后的字符串
     */
    private static String formatFileSize(long bytes) {
        if (bytes <= 0) return "0 B";

        String[] units = {"B", "KB", "MB", "GB", "TB"};
        int unitIndex = (int) (Math.log10(bytes) / Math.log10(1024));
        double size = bytes / Math.pow(1024, unitIndex);

        return String.format("%.2f %s", size, units[unitIndex]);
    }
}
